--[[
Holdout Example

	Underscore prefix such as "_function()" denotes a local function and is used to improve readability
	
	Variable Prefix Examples
		"fl"	Float
		"n"		Int
		"v"		Table
		"b"		Boolean
]]
local inspect = require('inspect')
--local ItemCore = require 'item_core'

if CCraftersGameMode == nil then
	CCraftersGameMode = class({})
end

-- Precache resources
function Precache( context )
	PrecacheModel( "models/heroes/morphling/morphling.vmdl", context )
	PrecacheModel( "models/heroes/broodmother/spiderling.vmdl", context )
	PrecacheModel( "models/items/warlock/warlocks_summoning_scroll/warlocks_summoning_scroll.vmdl", context )
	PrecacheModel( "models/creeps/neutral_creeps/n_creep_dragonspawn_a/n_creep_dragonspawn_a.vmdl", context )
	PrecacheResource("particle","particles/neutral_fx/troll_heal.vpcf", context)
	PrecacheResource("particle","particles/units/heroes/hero_stormspirit/stormspirit_ball_lightning_trail_base_elec.vpcf", context)
	PrecacheItemByNameSync( "item_bag_of_gold", context )
end

-- Actually make the game mode when we activate
function Activate()
	GameRules.crafters = CCraftersGameMode()
	GameRules.crafters:InitGameMode()
	GameRules.crafters:SpawnInitailUnits()
	--Entities:FindAllByClassname('dota_base_game_mode')[1]:SetThink('onThink', GameRules.crafters:SpawnInitailUnits(), 5)
end


function CCraftersGameMode:InitGameMode()
	GameRules:SetTimeOfDay( 0.75 )
	GameRules:SetHeroRespawnEnabled( true )
	GameRules:SetUseUniversalShopMode( true )
	GameRules:SetHeroSelectionTime( 0.0 )
	GameRules:SetPreGameTime( 10.0 )
	GameRules:SetPostGameTime( 60.0 )
	GameRules:SetTreeRegrowTime( 60.0 )
	GameRules:SetHeroMinimapIconSize( 400 )
	GameRules:SetCreepMinimapIconScale( 0.7 )
	GameRules:SetRuneMinimapIconScale( 0.7 )
	GameRules:SetGoldTickTime( 60.0 )
	GameRules:SetGoldPerTick( 0 )
	GameRules:GetGameModeEntity():SetRemoveIllusionsOnDeath( true )
	GameRules:GetGameModeEntity():SetTopBarTeamValuesOverride( true )
	GameRules:GetGameModeEntity():SetTopBarTeamValuesVisible( false )
	Entities:FindAllByClassname('dota_base_game_mode')[1]:SetCustomHeroMaxLevel(500)
	Entities:FindAllByClassname('dota_base_game_mode')[1]:SetCustomXPRequiredToReachNextLevel(self:HeroLevels())
	Entities:FindAllByClassname('dota_base_game_mode')[1]:SetUseCustomHeroLevels(true)

	CreateHeroForPlayer("npc_dota_hero_sven", PlayerInstanceFromIndex(1))
	FireGameEvent("hero_picker_hidden", nil)

	ListenToGameEvent( "entity_killed", Dynamic_Wrap( CCraftersGameMode, "OnEntityKilled" ), self )
end

function CCraftersGameMode:HeroLevels()
	local levels = { 0 }
	local exp = 40;
	for i=1,500 do 
	 	table.insert(levels, exp)
		exp = exp + 40 * i
	end
	return levels
end

--Items

local lootTable = { 
	{ 
		{"item_bag_of_gold", 0.01},
		{"item_shield_1", 0.01},
		{"item_spell_heal", 0.99}
	}, 
	{
		{"item_bag_of_gold", 0.01}
	},
	{
		{"item_bag_of_gold", 0.01}
	}, 
	{
		{"item_bag_of_gold", 0.01}
	}, 
}

function CCraftersGameMode:CreateItemForUnit(unit)
	for key,value in pairs(lootTable[unit:GetLevel()]) do
		if(value[2] >= math.random()) then
			CreateItemOnPositionSync(unit:GetOrigin(),CreateItem(value[1], nil, nil ))
			return nil
		end
	end
end

--Spawners

function CCraftersGameMode:createUnit(unit)
	self:Precache(unit:GetName())
	local new = CreateUnitByName(unit:GetContext("Class"), unit:GetOrigin(), true, nil, nil, DOTA_TEAM_BADGUYS)
	--new:SetContext("Class", unit:GetContext("Class"), 0)
	--new:SetChampion( true )
	return new
end

function CCraftersGameMode:OnEntityKilled( event )
	local killedUnit = EntIndexToHScript( event.entindex_killed )
	--local class = killedUnit:GetContext("Class")

	if killedUnit:IsRealHero()  then
		killedUnit:SetTimeUntilRespawn(1);
		--killedUnit:RespawnHero(false, true, true);
	else 
		self:CreateItemForUnit(killedUnit)
	end
end

function CCraftersGameMode:Precache(name)
	PrecacheUnitByNameAsync( name, function( sg ) self._sg = sg end )
end

function CCraftersGameMode:SpawnInitailUnits()
	local entSpawners = Entities:FindAllByClassname("npc_dota_scripted_spawner")
	for key,value in pairs(entSpawners) do
		--self:createUnit(value)
		local entUnit = CreateUnitByName(value:GetName(), value:GetOrigin(), true, nil, nil, DOTA_TEAM_BADGUYS )
		entUnit:SetContext("Class", value:GetName(), 0)
		entUnit:SetChampion( true )
		function entUnit:respawn()
			
			if (self:IsAlive() == false) then
				if (self:GetContext('Dead') == "true") then
					self:RespawnUnit();
					self:SetContext('Dead', "false", 0)
				else
					self:SetContext('Dead', "true", 0)
					return 5;
				end
			end
			return 2;
		end
		entUnit:SetThink("respawn", entUnit, 2)
		--entUnit:CreatureLevelUp( 24 )
	end
end

